﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Threading;
using CeA.Reports.Atendimento.DataAccess.DTO;
using CeA.Reports.Atendimento.DataAccess.Criteria;
using Qtech.Reports.Atendimento.Services;
using System.Linq;

namespace CeA.Reports.Atendimento.Web.admin {
    /// <summary>
    /// Summary description for planejamentoservice
    /// </summary>
    [WebService(Namespace = "http://qweb.cogtivesystems.com.br/services")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    [ScriptService]
    public class planejamentoservice : System.Web.Services.WebService {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public JSONDataTable BuildDataTable(int ano, int mes, int loja) {
            List<HoraDTO> horaRows = CadastroFacade.FindHora();

            var newHoraRows = from t in horaRows select t;

            List<JSONDataTableColumn> cols = newHoraRows.Select(x => 
                    new JSONDataTableColumn() { sTitle = x.HoraString }).ToList<JSONDataTableColumn>();

            cols.Insert(0, new JSONDataTableColumn("Período"));

            
            List<PlanejamentoDTO> planRows = CadastroFacade.FindPlanejamento(new PlanejamentoCriteria() {
                Ano = ano,
                Mes = mes,
                LojaId = loja   //,Dia = 1
            });
            
            List<string[]> rows = new List<string[]>();
            
            
            List<string> tmp = new List<string>();
            tmp.Insert(0, "dd/mm");

            List<string> tmp2 = new List<string>();
            tmp2.Insert(0, "dd/mm");

            string otherDia = null;

            foreach (PlanejamentoDTO row in planRows) {
                string actualDia = row.Dia.Dia.ToString().PadLeft(2, '0') + "/" + row.Dia.Mes.ToString().PadLeft(2, '0');
                if (otherDia == null) otherDia = actualDia;

                if (actualDia != otherDia) {
                    otherDia = row.Dia.Dia.ToString().PadLeft(2, '0') + "/" + row.Dia.Mes.ToString().PadLeft(2, '0');
                    
                    rows.Add(tmp.ToArray());
                    rows.Add(tmp2.ToArray());
                    
                    tmp = new List<string>();
                    tmp.Insert(0, "dd/mm");

                    tmp2 = new List<string>();
                    tmp2.Insert(0, "dd/mm");
                }

                tmp.Add(row.QtdeMesaEstatistica.ToString());
                tmp[0] = row.Dia.Dia.ToString().PadLeft(2, '0') + "/" + row.Dia.Mes.ToString().PadLeft(2, '0');

                //string html = string.Format("<span type='hidden' value='{0}' id='codigo'></span><span id='valor'>{1}</span>", row.Id, row.QtdeMesaPlanejada.ToString());
                string html = string.Format("<input type='hidden' value='{0}' id='codigo'/><span id='valor'>{1}</span>", row.Id, row.QtdeMesaPlanejada.ToString());
                tmp2.Add(html /*row.QtdeMesaPlanejada.ToString()*/);
                tmp2[0] = row.Dia.Dia.ToString().PadLeft(2, '0') + "/" + row.Dia.Mes.ToString().PadLeft(2, '0');

                otherDia = row.Dia.Dia.ToString().PadLeft(2, '0') + "/" + row.Dia.Mes.ToString().PadLeft(2, '0');
            }


            #region -- Não Utilizado: Apenas para referência --------------------------------------
            /*
            //rows.Add(tmp.ToArray());

            //row.QtdeMesaPlanejada;

            
            
            string[] row1a = new string[] { "01/08", "4", "4", "3", "5", "2", "2", "4", "5", "5", "1", 
                                                     "1", "4", "4", "3", "5", "2", "2", "4", "5", "5", 
                                                     "1", "1", "4", "4", "3", "5", "2", "2", "4", "5", "5"};
            
            string[] row1b = new string[] { "01/08", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", 
                                                     "X", "X", "X", "X", "X", "X", "X", "X", "X", "X",
                                                     "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X"};


            string[] row2a = new string[] { "02/08", "3", "5", "2", "2", "3", "5", "4", "1", "3", "2", 
                                                     "3", "5", "2", "2", "3", "5", "4", "1", "3", "2",
                                                     "3", "5", "2", "2", "3", "5", "4", "1", "3", "2", "3" };
            
            string[] row2b = new string[] { "02/08", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", 
                                                     "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y",
                                                     "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y" };
            
            rows.Add(row1a);
            rows.Add(row1b);
            rows.Add(row2a);
            rows.Add(row2b);
            */
            #endregion


            JSONDataTable data = new JSONDataTable() {
                aaData = rows,
                aoColumns = cols
            };

            return data;
        }


        /// <summary>
        /// Obtem todos os eventos de dia de Pico e Vale de acordo com parâmetros informados.
        /// </summary>
        /// <param name="ano">Ano de consulta</param>
        /// <param name="mes">Mês de consulta</param>
        /// <returns>Lista contendo todos os registros de evento de Pico ou Vale para o Ano/Mes informado.</returns>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public List<FullCalendarEventObject> GetEvents(int ano, int mes) {
            DiaCriteria filter = new DiaCriteria();
            filter.Ano = ano;
            filter.Mes = mes;

            DiaPicoDTO dto = new DiaPicoDTO();

            List<DiaPicoDTO> ds = CadastroFacade.FindDiaPico(filter);
            var set = from t in ds where t.TipoDia == TipoDia.Pico select t;

            return set.Select(x => new FullCalendarEventObject(new DateTime(x.Ano, x.Mes, x.Dia)) {
                id = x.Id,
                allDay = true,
                title = x.TipoDia.ToString()
            }).ToList<FullCalendarEventObject>();
        }

        /// <summary>
        /// Atualiza a tabela de planejamento com informação da procedure de estatistica.
        /// </summary>
        /// <param name="ano">Ano da incidencia</param>
        /// <param name="mes">Mes da incidencia</param>
        /// <param name="loja">Id da Loja</param>
        /// <param name="branchno">Numero controle do Qmatic</param>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public void BuildDataProcedure(int ano, int mes, int loja, int branchno)
        {
            PlanejamentoCriteria criteria = new PlanejamentoCriteria();
            criteria.Ano = ano;
            criteria.Mes = mes;
            criteria.LojaId = loja;
            criteria.QmaticBranchno = branchno;
            CadastroFacade.CarregarEstatistica(criteria);
        }

        /// <summary>
        /// Atualiza um evento de Pico para Vale de acordo com o código do evento
        /// </summary>
        /// <param name="id">Código do evento de pico (tabela DIA)</param>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public void UpdateEvent(int id) {
            DiaPicoDTO dto = new DiaPicoDTO() { Id = id, TipoDia = TipoDia.Vale };
            CadastroFacade.UpdateDiaPico(dto);
        }

        
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public int CreateEvent(int ano, int mes, int dia) {
            
            DiaPicoDTO dto = new DiaPicoDTO() {
                TipoDia = TipoDia.Pico,
                Ano = ano,
                Mes = mes,
                Dia = dia
            };
            
            CadastroFacade.UpdateDiaPico(dto);

            return dto.Id;
        }


        /// <summary>
        /// Atualiza um evento de Pico para Vale de acordo com o código do evento
        /// </summary>
        /// <param name="id">Código do evento de pico (tabela DIA)</param>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public void UpdatePlanejamento(int id, decimal val) {
            PlanejamentoDTO dto = new PlanejamentoDTO() {Id = id,  QtdeMesaPlanejada = val};
            CadastroFacade.UpdatePlanejamento(dto);
        }



        /// <summary>
        /// Seriazlia um objeto qualquer no formato JSON
        /// </summary>
        /// <param name="any">Quaquer objeto com a atributo [Serializable].</param>
        /// <returns></returns>
        private string Serialize(object any) {
            string output = JsonConvert.SerializeObject(any, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
            Console.WriteLine(output);
            return output;
        }

        public class JSONDataTableColumn {
            public JSONDataTableColumn() { }
            public JSONDataTableColumn(string title) {
                sTitle = title;
            }

            public string sTitle { get; set; }
            public string sClass { get; set; }
        }

        public class JSONDataTable {
            public object aaData { get; set; }
            public object aoColumns { get; set; }
        }
    }


    /// <summary>
    /// Representa parcialmente um evento do calendário de acordo com 
    /// http://arshaw.com/fullcalendar/docs/event_data/Event_Object/
    /// </summary>
    public class FullCalendarEventObject {
        private DateTime m_start;
        private DateTime m_end;

        public FullCalendarEventObject(DateTime start) {
            this.m_start = start;
        }

        public int id { get; set; }
        public string title { get; set; }
        public bool allDay { get; set; }
        //public string url { get; set; }
        
        public string start { 
            get {
                return m_start.ToString("s");
            }
            set {
                m_start = Convert.ToDateTime(value);
            } 
        }

        public string end {
            get {
                if (m_end == DateTime.MinValue) return null;
                return m_end.ToString("s");
            }
            set {
                m_end = Convert.ToDateTime(value);
            }
        }
    }


    /// <summary>
    /// Representa um filtro JSON de mes e ano para a consulta dos dias de pico/vale.
    /// </summary>
    public class Filtro {
        public string Ano { get; set; }
        public string Mes { get; set; }
    }
}
